<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.account"
        placeholder="登录账号"
        clearable
        class="filter-item"
        style="width: 280px"
        size="small"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.username"
        placeholder="用户名"
        clearable
        class="filter-item"
        style="width: 280px"
        size="small"
        @keyup.enter.native="handleFilter"
      />

      <el-select
        v-model="listQuery.enabled"
        placeholder="状态"
        clearable
        class="filter-item"
        style="width: 120px"
        size="small"
      >
        <el-option key="true" label="正常" value="true" />
        <el-option key="false" label="禁用" value="false" />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        size="small"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        size="small"
        @click="handleCreate"
      >
        新建
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="ID" width="60">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="登录账号" width="150">
        <template slot-scope="scope">
          {{ scope.row.account }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="enabledStatusFilter(scope.row.enabled)">
            {{ scope.row.enabled ? "正常" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="用户名">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          <el-tag>{{ showRoleName(scope.row.roles) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createdTime }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间">
        <template slot-scope="scope">
          {{ scope.row.updatedTime }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="120"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            class="btn-cancel"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="fetchData"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="80px"
        size="small"
        style="width: 500px; margin-left: 50px"
      >
        <el-form-item label="登录账号" prop="method">
          <el-input
            v-model="temp.account"
            :disabled="dialogStatus === 'update'"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="method">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item
          v-show="dialogStatus === 'create'"
          label="密码"
          prop="method"
        >
          <el-input v-model="temp.password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="temp.roles"
            clearable
            filterable
            multiple
            class="filter-item"
            style="width: 430px"
          >
            <el-option
              v-for="item in roleCodeList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-switch
            v-model="temp.enabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          size="small"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, addUser, updateUser, deleteUser } from '@/api/userManage'
import { getRoleCodeList } from '@/api/role'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import md5 from 'js-md5'

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      roleCodeList: null,
      roleCodeMap: {},
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        account: undefined,
        username: undefined,
        enabled: undefined
      },
      textMap: {
        update: '编辑用户',
        create: '新增用户'
      },
      temp: {
        id: undefined,
        account: undefined,
        username: undefined,
        enabled: true,
        roles: ['user']
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        account: [
          { required: true, message: '请输入登录账号', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchRoleCodeList()
    this.fetchData()
  },
  methods: {
    fetchRoleCodeList() {
      getRoleCodeList().then((response) => {
        this.roleCodeList = response.data
        this.roleCodeMap = new Map(
          this.roleCodeList.map((item) => [item.code, item.name])
        )
      })
    },
    fetchData() {
      this.listLoading = true
      listUser(this.listQuery).then((response) => {
        this.total = response.data.total
        this.list = response.data.items
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.fetchData()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        account: undefined,
        username: undefined,
        enabled: true,
        roles: ['user']
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('是否确认删除此用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDelete(row)
      })
    },
    doDelete(row) {
      deleteUser({ id: row.id }).then(() => {
        // const index = this.list.findIndex(v => v.id === this.temp.id)
        // this.list.splice(index, 1, this.temp)
        this.fetchData()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData).then(() => {
            const index = this.list.findIndex((v) => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
          })
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.password = md5(tempData.password)
          addUser(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
          })
        }
      })
    },
    enabledStatusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'info'
      }
      return statusMap[status]
    },
    showRoleName(roles) {
      const roleNameArr = []
      for (let index = 0; index < roles.length; index++) {
        const element = roles[index]
        roleNameArr[index] = this.roleCodeMap.get(element)
      }
      return roleNameArr.join(',')
    }
  }
}
</script>
